<template>
  <div class="h100">
    <s-table
      class="h100"
      :columns="columns"
      :loading="loading"
      :data-source="lists"
      :showPagination="false"
      :rowKey="(record, index) => record.index"
      ref="table">
      <!-- 供应商ID -->
      <template #supplierId="text, record">
        <!-- 编辑的时候不能更改 -->
        <a-input
          @change="handlerChange(record,'businessId',$event)"
          v-if="!record.id"
          :v-model="record.businessId"
          :maxLength="20"
          :class="{hasError:record.businessIdError}" />
        <table-ellipsis v-else :text="text || '-'"></table-ellipsis>
      </template>
      <!-- 供应商中文全称 -->
      <template #supplierZhName="text, record">
        <a-input
          @change="handlerChange(record,'fullName',$event)"
          v-if="record.editable"
          v-model="record.fullName"
          :maxLength="50"
          :class="{hasError:record.fullNameError}" />
        <table-ellipsis v-else :text="text || '-'"></table-ellipsis>
      </template>
      <!-- 供应商中文简称 -->
      <template #supplierZhSortName="text, record">
        <a-input
          @change="handlerChange(record,'shortName',$event)"
          v-if="record.editable"
          v-model="record.shortName"
          :maxLength="20"
          :class="{hasError:record.shortNameError}" />
        <table-ellipsis v-else :text="text || '-'"></table-ellipsis>
      </template>
      <!-- 供应商英文简称 -->
      <template #supplierEnSortName="text, record ">
        <a-input
          @change="handlerChange(record,'shortNameEn',$event)"
          v-if="record.editable"
          v-model="record.shortNameEn"
          :maxLength="20"
          :class="{hasError:record.shortNameEnError}" />
        <table-ellipsis v-else :text="text || '-'"></table-ellipsis>
      </template>
      <!-- 供应商英文全称(代号) -->
      <template #supplierEnName="text, record">
        <a-input
          @change="handlerChange(record,'fullNameEn',$event)"
          v-if="record.editable"
          v-model="record.fullNameEn"
          :maxLength="20"
          :class="{hasError:record.fullNameEnError}" />
        <table-ellipsis v-else :text="text || '-'"></table-ellipsis>
      </template>
      <template #operation="text, record, index">
        <!-- 编辑与删除 -->
        <div v-if="record.editable === false" key="editaction">
          <auth-text @click="editRecord(record)" :auth="''" style="margin-right: 8px">
            {{ $t('edit') }}
          </auth-text>
          <auth-text :auth="''" @click="deleteList(record,index)">
            {{ $t('delete') }}
          </auth-text>
        </div>
        <!-- 保存与取消 -->
        <div v-else key="saveaction" style="margin-right: 8px">
          <auth-text :auth="''" @click="saveData(record)">
            {{ $t('save') }}
          </auth-text>
          <auth-text :auth="''" @click="cancelSave(record, index)">
            {{ $t('cancel') }}
          </auth-text>
        </div>
      </template>
    </s-table>
  </div>
</template>
<script>
import { STable } from '@/components'
import { supplierlTbColumns } from '../config/list'
import AuthText from '@/components/AuthText'
import tableEllipsis from '@/components/Ellipsis/TableEllipsis'
import supplierApi from '@/api/modules/system/supplier'
// 需要检测的字段标志符
const checkFieldConfig = {
  businessIdError: false,
  fullNameError: false,
  fullNameEnError: false,
  shortNameError: false,
  shortNameEnError: false
}
const oneRecord = {
  id: '',
  businessId: '',
  fullName: '',
  fullNameEn: '',
  remark: '',
  shortName: '',
  shortNameEn: '',
  editable: true,
  error: false,
  index: -1,
  ...checkFieldConfig
}
const canEditField = ['shortNameEn', 'fullName', 'fullNameEn', 'shortName']
export default {
  components: {
    STable,
    AuthText,
    tableEllipsis
  },
  data () {
    return {
      columns: supplierlTbColumns,
      lists: [],
      loading: false,
      pageInfo: {
        pageNo: 1,
        pageSize: 1000
      },
      rules: {
        businessId: {
          required: true,
          msg: ''
        },
        fullName: {
          required: true,
          msg: ''
        },
        fullNameEn: {
          required: true,
          msg: ''
        },
        shortName: {
          required: true,
          msg: ''
        },
        shortNameEn: {
          required: true,
          msg: ''
        }
      }
    }
  },
  created () {
    this.getLists()
  },
  methods: {
    checkIsEmpty (value) {
      const val = value ? value.replace(/^\s+|\s+$/g, '') : ''
      return val.length === 0
    },
    handlerChange (record, key, ev) {
      if (this.checkIsEmpty(ev.target.value)) {
        // eslint-disable-next-line no-param-reassign
        record[key + 'Error'] = true
        // eslint-disable-next-line no-param-reassign
        record[key] = ev.target.value
      } else {
        // eslint-disable-next-line no-param-reassign
        record[key + 'Error'] = false
        // eslint-disable-next-line no-param-reassign
        record[key] = ev.target.value.replace(/^\s+|\s+$/g, '')
      }
    },

    getLists () {
      const params = {
        ...this.pageInfo
      }
      supplierApi.getSupplierPageList(params).then(res => {
        if (res.data) {
          this.lists = res.data.map((item) => {
            return {
              id: item.id,
              businessId: item.businessId,
              fullName: item.fullName,
              fullNameEn: item.fullNameEn,
              remark: item.remark,
              shortName: item.shortName,
              shortNameEn: item.shortNameEn,
              editable: false,
              error: false,
              index: item.id,
              ...checkFieldConfig
            }
          })
        }
      })
    },
    // 添加记录
    addRecord () {
      const objItem = {
        ...oneRecord,
        index: Math.random()
      }
      this.lists.unshift(objItem)
    },
    editRecord (record) {
      for (let i = 0; i < canEditField.length; i = i + 1) {
        const zd = canEditField[i]
        const copyZd = zd + 'Copy'
        // eslint-disable-next-line no-param-reassign
        record[copyZd] = record[zd]
      }
      // eslint-disable-next-line no-param-reassign
      record.editable = true
    },
    // 取消保存
    cancelSave (record, index) {
      const vm = this
      this.$confirm({
        title: vm.$t('cancelSave'),
        content: vm.$t('cancelSaveTip'),
        onOk () {
          if (record.id) {
            // 编辑的时候(将数据还原)
            for (let i = 0; i < canEditField.length; i = i + 1) {
              const zd = canEditField[i]
              const copyZd = zd + 'Copy'
              // eslint-disable-next-line no-param-reassign
              record[zd] = record[copyZd]
              // eslint-disable-next-line no-param-reassign
              record[zd + 'Error'] = false
            }
            // eslint-disable-next-line no-param-reassign
            record.editable = false
          } else {
            // 添加的时候
            vm.lists.splice(index, 1)
          }
        },
        onCancel () { }
      })
    },
    saveData (data) {
      // 保存数据 api请求
      if (!this.checkData(data)) {
        return
      }
      const method = data.id ? 'editSupplier' : 'addSupplier'
      const saveData = {
        id: data.id,
        businessId: data.businessId,
        fullName: data.fullName,
        fullNameEn: data.fullNameEn,
        remark: data.remark,
        shortName: data.shortName,
        shortNameEn: data.shortNameEn
      }
      supplierApi[method](saveData).then(res => {
        // eslint-disable-next-line no-param-reassign
        data.editable = false
        if (!data.id) {
          // eslint-disable-next-line no-param-reassign
          data.id = res.data
        }
        this.$message.success(this.$t('successfullyOperation'))
      })
    },
    checkData (data) {
      let checkOk = true
      console.log(data, 'data')
      // eslint-disable-next-line no-restricted-syntax
      for (const key in data) {
        if (this.rules[key] && this.rules[key].required) {
          if (this.checkIsEmpty(data[key])) {
            // eslint-disable-next-line no-param-reassign
            data[key + 'Error'] = true
            checkOk = false
          } else {
            // eslint-disable-next-line no-param-reassign
            data[key + 'Error'] = false
          }
        }
      }
      if (!checkOk) {
        this.$message.error(this.$t('completeInformation'))
      }
      return checkOk
    },
    // 删除
    deleteList (record, index) {
      const vm = this
      this.$confirm({
        title: vm.$t('deleteSupplier'),
        content: vm.$t('deleteSupplierTip').replace('__CONTENT__', '（' + record.fullName + '）'),
        class: 'confirmStyle',
        width: 378,
        onOk () {
          // api请求
          supplierApi.deleteSupplier({ ids: [record.id] }).then(() => {
            vm.lists.splice(index, 1)
            vm.$message.success(vm.$t('successfullyOperation'))
          })
        },
        onCancel () { }
      })
    }
  }
}
</script>
